﻿using Domain.Entitys.Base_Manage;
using Domain.IRepositorys.Base_Manage;

namespace EFCore.Repositorys.Base_Manage
{
    public class JurisdictionRepository : IJurisdictionRepository
    {
        private readonly MyDbContext myDbContext;

        public JurisdictionRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }

        /// <summary>
        /// 查询出角色对应的权限
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Trees> GetJurisdictions(int rolesId)
        {
            //查询角色对应的权限
            var jurisdictions = myDbContext.Sys_Role_Menu
                .Where(rm => rm.Role_id == rolesId)
                .Join(
                    myDbContext.Sys_Menu,
                    rm => rm.Menu_id,
                    j => j.Menu_id,
                    (rm, j) => j  // 直接返回Jurisdiction对象
                )
                .ToList();
            List<Trees> trees = CreateMenu(jurisdictions, 0);
            return trees;
        }

        /// <summary>
        /// 把二维结构转换为层次结构
        /// </summary>
        /// <param name="rolesJurisdictions"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public List<Trees> CreateMenu(List<Sys_Menu> jurisdictions, int groupId)
        {
            //获取父级数据
            List<Sys_Menu> jurisdictions1 = jurisdictions.Where(j => j.Parent_id == groupId).ToList();
            List<Trees> trees = new List<Trees>();
            foreach (Sys_Menu jurisdiction in jurisdictions1)
            {
                Trees t = new Trees()
                {
                    JurId = jurisdiction.Menu_id,
                    JurName = jurisdiction.Menu_name,
                    GroupId = jurisdiction.Parent_id,
                    JurAddress = jurisdiction.Menu_address,
                    children = CreateMenu(jurisdictions, jurisdiction.Menu_id)
                };
                trees.Add(t);
            }
            return trees;
        }
    }
}
